from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
import Ui_pelangganSrc

class PelangganSrc(QDialog, Ui_pelangganSrc.Ui_pelangganSrc):
  def __init__(self, dbConn, parent=None):
        super(PelangganSrc, self).__init__(parent)
        self.setupUi(self)
        self.db = dbConn
        self.initData()
        self.srcModel = QSqlQueryModel(self)
        self.srcModel.setHeaderData(2, Qt.Horizontal, QVariant("Nama"))
        self.srcModel.setHeaderData(3, Qt.Horizontal, QVariant("No MMC"))
        self.srcModel.setHeaderData(4, Qt.Horizontal, QVariant("Alamat"))
        self.srcModel.setHeaderData(5, Qt.Horizontal, QVariant("Kota"))
        
        self.search_tv.setModel(self.srcModel)
        self.search_tv.setSelectionMode(QTableView.SingleSelection)
        self.search_tv.setSelectionBehavior(QTableView.SelectRows)
        self.search_tv.resizeColumnsToContents()
        self.id = ""

  def getID(self):
    return self.id
    
  @pyqtSignature("")
  def on_cariBtn_clicked(self):       
      qStr = "select id_pelanggan, kode_pelanggan, nama, no_kartu, alamat1, kota1 from pelanggan"
      filt = ""
      urut = " order by nama "
      if self.nama_cb.checkState() == Qt.Checked:
          filt = filt + " nama like '"+self.nama.text()+"%' and "
      if self.no_cb.checkState() == Qt.Checked:
          filt = filt + " no_kartu like '"+self.no.text()+"%' and "
          
      if filt != "":
          filt = " where "+filt.left(len(filt)-4)
          
      qStr = qStr + filt + urut
      self.srcModel.setQuery(qStr, self.db)
      self.search_tv.setColumnHidden(0, True)
      self.search_tv.setColumnHidden(1, True)
      self.search_tv.setColumnWidth(2, 150)
      self.search_tv.setColumnWidth(3, 75)
      self.search_tv.setColumnWidth(4, 200)
      self.search_tv.resizeRowsToContents()

  @pyqtSignature("")
  def on_pilihBtn_clicked(self):
      index = self.search_tv.currentIndex()
      if index.isValid():
          brs = self.srcModel.record(index.row())
          self.id = brs.value("id_pelanggan").toString()
          self.done(1)

  @pyqtSignature("")
  def on_batalBtn_clicked(self):
      self.close()
      
  @pyqtSignature("")
  def on_nama_editingFinished(self):
      if not self.nama.text().isEmpty():
          self.nama_cb.setCheckState(Qt.Checked)
      else:
          self.nama_cb.setCheckState(Qt.Unchecked)
          
  @pyqtSignature("")
  def on_no_editingFinished(self):
      if not self.no.text().isEmpty():
          self.no_cb.setCheckState(Qt.Checked)
      else:
          self.no_cb.setCheckState(Qt.Unchecked)

  def initData(self):
      hari = QDate.currentDate()

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    form = PelangganEdit()
    form.show()
    app.exec_()
